package com.example.module_word.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.toRect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.drawOutline
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.module_word.R
import com.example.module_word.activity.CameraActivity
import com.example.module_word.activity.DanCiActivity
import com.example.module_word.activity.IndexStackActivity
import com.example.module_word.activity.LexiconActivity
import com.example.module_word.activity.PlanActivity
import com.example.module_word.search.activity.SearchActivity
import com.example.module_word.viewmodel.HomeViewModel
import com.example.module_word.widget.noRippleClickable
import com.fenghuajueli.libbasecoreui.utils.AdUtil
import com.ll.permission.AllowPermissionUseCase

class WordFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                HomeScreen()
            }
        }
    }
}

private val tabList = listOf(
    "拍照翻译" to R.mipmap.sy_btn_pzfy,
    "制定计划" to R.mipmap.sy_btn_zdjh,
    "词单" to R.mipmap.sy_btn_cd,
)

@Composable
private fun HomeScreen(modifier: Modifier = Modifier) {

    val context = LocalContext.current
    val vm = viewModel<HomeViewModel>()

    LifecycleResumeEffect(key1 = Unit) {
        vm.refreshTheData()
        onPauseOrDispose { }
    }
    val onClick: (String) -> Unit = remember {
        {
            when (it) {
                "搜索" -> {
                    AdUtil.clickAdAndPay(context as FragmentActivity, 1, -1) {
                        SearchActivity.start(context)
                    }
                }

                "签到" -> {
                    AdUtil.clickAdAndPay(context as FragmentActivity, 1) {
                        vm.saveSignInState()
                    }
                }

                "拍照翻译" -> {
                    AdUtil.clickAdAndPayWithIncentiveMode(context as FragmentActivity, 1) {
                        AllowPermissionUseCase.useCamera(
                            context as FragmentActivity,
                            description = "用于实现拍照翻译的功能，需要访问您的相机权限，如若拒绝，将无法使用上述功能"
                        ) {
                            context.startActivity(
                                Intent(
                                    context,
                                    CameraActivity::class.java
                                )
                            )
                        }
                    }
                }

                "制定计划" -> {
                    AdUtil.clickAdAndPay(context as FragmentActivity, 1, -1) {
                        context.startActivity(
                            Intent(context, PlanActivity::class.java).putExtra(
                                "kind",
                                vm.currentKind.value
                            )
                        )
                    }
                }

                "词单" -> {
                    AdUtil.clickAdAndPay(context as FragmentActivity, 1, -1) {
                        context.startActivity(
                            Intent(context, LexiconActivity::class.java).putExtra(
                                "kind",
                                vm.currentKind.value
                            ).putExtra(
                                "jrdc",
                                vm.wordOfTheDay.value
                            )
                        )
                    }
                }

                "切换词库" -> {
                    AdUtil.clickAdAndPay(context as FragmentActivity, 1, -1) {
                        context.startActivity(Intent(context, IndexStackActivity::class.java))
                    }
                }

                "开始学习吧" -> {
                    AdUtil.clickAdAndPay(context as FragmentActivity, 1) {
                        if (vm.wordOfTheDay.value == "暂无计划") {
                            context.startActivity(
                                Intent(context, PlanActivity::class.java).putExtra(
                                    "kind",
                                    vm.currentKind.value
                                )
                            )
                        } else {
                            context.startActivity(
                                Intent(context, DanCiActivity::class.java).putExtra(
                                    "kind",
                                    vm.currentKind.value
                                ).putExtra(
                                    "jrdc",
                                    vm.wordOfTheDay.value
                                )
                            )
                        }
                    }
                }
            }
        }
    }



    Box(modifier = Modifier.background(Color(0xFFffffff))){
        Column {
            Image(
                painter = painterResource(id = R.mipmap.banner_dc),
                contentDescription = null,
                modifier = Modifier.fillMaxWidth(),
                contentScale = ContentScale.FillBounds
            )
            Image(
                painter = painterResource(id = R.mipmap.word_bg),
                contentDescription = null,
                modifier = Modifier
                    .fillMaxWidth()
                    .offset(y = (-20).dp),
                contentScale = ContentScale.FillBounds
            )
        }

        Column(
            modifier = modifier
                .fillMaxSize()
//                .background(Color(0xFF3062F7))
                .statusBarsPadding()
                .verticalScroll(rememberScrollState())
//                .drawBehind {
//                    drawOutline(
//                        outline = Outline.Rounded(
//                            RoundRect(
//                                size
//                                    .toRect()
//                                    .copy(top = 142.dp.toPx()),
//                                topLeft = CornerRadius(20.dp.toPx()),
//                                topRight = CornerRadius(20.dp.toPx())
//                            )
//                        ), color = Color(0xFFF5F7FF)
//                    )
//                }
        ) {

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 28.dp, end = 19.dp, top = 8.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = vm.getDay(),
                        fontSize = 32.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Black
                    )
                    Text(
                        text = vm.getYearAndMonth(),
                        fontSize = 12.sp,
                        color = Color.White
                    )
                }

                Image(
                    painter = painterResource(id = R.mipmap.icon_search),
                    contentDescription = null,
                    modifier = modifier.noRippleClickable {
                        onClick.invoke("搜索")
                    })
            }

            Box(modifier = Modifier.padding(top = 30.dp)){
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 20.dp, end = 20.dp, top = 23.dp)
                        .background(Color.White, RoundedCornerShape(16.dp))
                        .padding(top = 11.dp, bottom = 13.dp),
                    horizontalArrangement = Arrangement.SpaceAround
                ) {
                    ImageAndTextCompose(
                        modifier = modifier.noRippleClickable {
                            onClick.invoke("签到")
                        },
                        image = if (vm.signInState.value) R.mipmap.sy_btn_qd_nor else R.mipmap.sy_btn_qd_sel,
                        text = "签到"
                    )
                    tabList.forEach {
                        ImageAndTextCompose(modifier = modifier.noRippleClickable {
                            onClick.invoke(it.first)
                        }, image = it.second, text = it.first)
                    }
                }
            }





            Box(modifier = Modifier) {
                Image(
                    painter = painterResource(id = R.mipmap.banner_bg_dcsj),
                    contentDescription = null,
                    modifier = Modifier
                        .align(Alignment.TopCenter)
                        .fillMaxSize()
                        .padding(top = 20.dp)
                )
                Column(
                    modifier = Modifier
                        .align(Alignment.TopCenter)
                        .fillMaxWidth()
                        .padding(start = 20.dp, end = 20.dp, top = 20.dp)

                ) {
                    Box(modifier = Modifier.fillMaxWidth()) {
                        Image(
                            painter = painterResource(id = R.mipmap.icon_qh),
                            contentDescription = null,
                            modifier = modifier
                                .align(Alignment.TopEnd)
                                .padding(16.dp, top = 35.dp, end = 40.dp)
                                .noRippleClickable {
                                    onClick.invoke("切换词库")
                                }
                        )
                    }
                    Text(
                        text = vm.currentKind.value,
                        fontSize = 16.sp,
                        color = Color(0xFFffffff),
                        fontWeight = FontWeight.Bold,
                        modifier = modifier.padding(top = 115.dp, start = 20.dp)
                    )
                    Text(
                        text = "打卡${vm.numberOfPunches.value}次",
                        fontSize = 12.sp,
                        color = Color(0xFFffffff),
                        fontWeight = FontWeight.Bold,
                        modifier = modifier.padding(top = 4.dp, start = 20.dp)
                    )

                    val progressAnimation by animateFloatAsState(
                        targetValue = (vm.theNumberOfWordsLearned.intValue.toFloat() / (vm.numberOfWords.intValue.takeIf { it != 0 }
                            ?: 1)),
                        label = "单词进度"
                    )

                    LinearProgressIndicator(
                        progress = { progressAnimation },
                        color = Color(0xFF3578FF),
                        trackColor = Color(0xFFF5F7FF),
                        drawStopIndicator = {},
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 12.dp, start = 20.dp, end = 40.dp)
                            .height(8.dp)
                            .background(Color(0xFFF5F7FF), RoundedCornerShape(8.dp))
                    )

                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(start = 20.dp, end = 40.dp, top = 6.dp, bottom = 13.dp),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = "已学单词",
                            fontSize = 10.sp,
                            color = Color(0xFFFFFFFF)
                        )
                        Text(
                            text = "${vm.theNumberOfWordsLearned.intValue}/${vm.numberOfWords.intValue}",
                            fontSize = 10.sp,
                            color = Color(0xFFFFFFFF)
                        )
                    }

                    Box(modifier = Modifier.padding(top = 13.dp)){
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 20.dp)
                                .padding(vertical = 11.dp),
                            horizontalArrangement = Arrangement.SpaceAround
                        ) {
                            listOf(
                                vm.wordOfTheDay to "今日单词",
                                vm.remainingWords to "剩余单词",
                                vm.numberOfDaysRemaining to "剩余天数",
                            ).forEach {
                                Column(
                                    modifier = modifier
                                        .weight(1f)
                                        .padding(end = 26.dp),
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    AutoSizeText(
                                        text = it.first.value,
                                        maxTextSize = 32.sp,
                                        color = Color(0xFFFFFFFF),
                                        fontWeight = FontWeight.W900,
                                    )
                                    Text(text = it.second, fontSize = 12.sp, color = Color(0x80ffffff))
                                }
                            }
                        }
                    }


                }

            }

            Text(
                text = "开始学习吧",
                fontSize = 16.sp,
                color = Color.White,
                textAlign = TextAlign.Center,
                modifier = modifier
                    .fillMaxWidth()
                    .padding(20.dp)
                    .background(Color(0xFFFFB81D), shape = RoundedCornerShape(28.dp))
                    .padding(vertical = 13.dp)
                    .noRippleClickable { onClick.invoke("开始学习吧") }
            )
        }
    }


}

@Composable
private fun RowScope.ImageAndTextCompose(modifier: Modifier = Modifier, image: Int, text: String) {
    Column(
        modifier = modifier.weight(1f),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(painter = painterResource(id = image), contentDescription = null)
        Spacer(modifier = Modifier.height(7.dp))
        Text(
            text = text,
            fontSize = 12.sp,
            color = Color(0xFF333333),
            fontWeight = FontWeight.Black
        )
    }
}

@Composable
private fun AutoSizeText(
    text: String,
    maxTextSize: TextUnit,
    color: Color = Color.Unspecified,
    fontWeight: FontWeight? = null
) {
    var textSize by remember { mutableStateOf(maxTextSize) }
    Text(
        text = text,
        fontSize = textSize,
        color = color,
        overflow = TextOverflow.Ellipsis,
        fontWeight = fontWeight,
        onTextLayout = { textLayoutResult ->
            if (textLayoutResult.lineCount > 1) {
                textSize = (textSize.value - 1).sp // 减小字体大小
            }
        }
    )
}